import copy
import os
import shutil

from src.log.logger import logger
from config.constants import FILES_CHECK_SUMS, FILES_SPDXID, SBOM_RPM_CPIO_TMP_PATH
from src.tools.query import RpmInfoQuery

class SbomFilesElementGenerate:
    """
    generate sbom files element info for rpm
    """

    def __init__(self, file_element, rpm_path):
        """
        init file_element, rpm_path
        Args:
            file_element:
            rpm_path:
        Returns:
        """

        self.file_element = file_element
        self.rpm_path = rpm_path
        self.extract_dir = SBOM_RPM_CPIO_TMP_PATH
        
    def generate_files_element(self):
        """
        merge new sbom  element jsons to sbom.json
        Args:
        Returns:
        """

        files_element = []
        RpmInfoQuery.extract_rpm(self.rpm_path, self.extract_dir)
        # 遍历解压后的目录并计算MD5哈希值
        for root, dirs, files in os.walk(self.extract_dir):
            for file in files:
                file_data = dict()
                file_data = copy.copy(self.file_element)
                file_path = os.path.join(root, file)
                md5_hash = RpmInfoQuery.compute_md5(file_path)
                file_name = os.path.basename(file_path)
                logger.info("start generate file_element data for: %s", file_name)
                true_file_path = file_path.replace(self.extract_dir, '')
                file_data['SPDXID'] = FILES_SPDXID.format(file_path=true_file_path, md5_sum=md5_hash)
                file_data['name'] = true_file_path
                file_data['checksums'] = copy.copy(FILES_CHECK_SUMS)
                file_data['checksums']['checksumValue'] = md5_hash
                logger.info("generate file_element data for: %s, %s", file_name, file_data)
                files_element.append(file_data)
                
        shutil.rmtree(self.extract_dir)  # 清理临时目录
        return files_element